package com.demo.service;


import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.Configuration;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.V1NodeList;
import io.kubernetes.client.openapi.models.V1PodList;
import io.kubernetes.client.openapi.models.V1ServiceList;
import io.kubernetes.client.util.ClientBuilder;
import io.kubernetes.client.util.KubeConfig;
import org.springframework.stereotype.Service;

import java.io.*;

@Service
public class KubernetesService {

    private final CoreV1Api coreV1Api;

    public KubernetesService() throws IOException, ApiException {
        // 尝试从类路径加载
        try (InputStream is = getClass().getClassLoader().getResourceAsStream("kubeconfig")) {
            if (is == null) {
                throw new FileNotFoundException("kubeconfig文件未找到。请确保它位于resources目录下");
            }

            ApiClient client = ClientBuilder
                    .kubeconfig(KubeConfig.loadKubeConfig(new InputStreamReader(is)))
                    .build();

            // 开发环境禁用SSL验证
            client.setVerifyingSsl(false);
            Configuration.setDefaultApiClient(client);
            this.coreV1Api = new CoreV1Api();
        }
    }

    public V1NodeList listNodes() throws IOException, ApiException {
        V1NodeList v1NodeList = coreV1Api.listNode("",true,
                null,null,null,null
        ,null,null,null,null);
        return v1NodeList;
    }

    public V1ServiceList listServices() throws Exception {
        V1ServiceList v1ServiceList = coreV1Api.listServiceForAllNamespaces(null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null
                , null);
        return v1ServiceList;
    }
//
    public V1PodList listPodsForAllNamespaces() throws IOException, ApiException {
        return coreV1Api.listPodForAllNamespaces(null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null);
    }
}
